// pages/mall/detail/index.js
const config = require('../../../utils/config.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    product: null,
    imgs: [],
    commentList:[],
    userInfo: null,
    content:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.data.product = {
      productId: options.productId
    }
    this._getProductDetail()
  },
  _getProductDetail() {
    let _this = this
    wx.request({
      url: config.HOST + '/product/byProductId/' + this.data.product.productId,
      success(res) {
        console.log(res.data)
        let imgs = []
        if(res.data.data.imgs!=undefined) {
          imgs = res.data.data.imgs.split(',')
        }
        _this.setData({
          product: res.data.data,
          imgs:imgs
        })
        _this._getCommentLIst()
      }
    })
  },
  // 获取商品评论
  _getCommentLIst() {
    let _this = this
    wx.request({
      url: config.HOST+'/product/commentList',
      data:{
        productId: this.data.product.productId,
        pageSize:9999
      },
      success(res) {
        _this.setData({
          commentList: res.data.data.list
        })
      }
    })
  },
  // 添加评论
  sendComment(e) {
    let _this = this
    let content = e.detail.value
    if(content.trim()=='') {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      })
      return ;
    }
    let token = wx.getStorageSync("token")
    wx.request({
      url: config.HOST +'/product/addComment',
      data: {
        token,
        productId: this.data.product.productId,
        content
      },
      success(res) {
        console.log(res.data)
        if(res.data.status==200) {
          wx.showToast({
            title: '评论成功',
          })
          if (_this.data.userInfo==null) {
            _this.data.userInfo = JSON.parse(wx.getStorageSync("userInfo"))
          }
          //添加自己评论内容
          let comm = {
            username: _this.data.userInfo.name,
            headImg:_this.data.userInfo.headimg,
            createDate: new Date(),
            content: content,
            commentId: new Date()
          }
          _this.data.commentList.unshift(comm)
          _this.setData({
            commentList: _this.data.commentList,
            content:''
          })
        }else {
          wx.showToast({
            title: '评论失败',
            icon: 'none'
          })
        }
      }
    })
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.product.user.phone,
    })
  },
  addorder() {
    // 如果是自销商品让买家自己联系
    app.globalData.product = this.data.product
    if (this.data.product.status==0) {
      wx.navigateTo({
        url: '../orderResult/index?cod=2',
      })
    }
    wx.navigateTo({
      url: '../order/index',
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})